//
//  DiaryExt.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/7.
//

import Foundation
class DiaryExt{
    
    //根据评论，获取最新的RoleBean
    static func getRole(_ bean: DiaryCommentBean?) async throws -> RoleBean? {
        if (bean == nil) { return nil }
        let role = bean?.role
        if role?.isBot() == true {
            //获取最新数据
            guard let aiRole = try await BackupsManager.shared.getDelegateConfig()?.getAiRole(roleId: role?.roleId ?? "") else { return nil }
            return RoleBean.get(aiRole)
        } else {
            bean?.role?.showName = userManager.getName()
            bean?.role?.avatar = userManager.getAvatar()
            return bean?.role
        }
    }
    
    //根据来信，获取最新的RoleBean
    static func getRole(_ bean: WeeklyLetterBean?) async throws -> RoleBean? {
        if (bean == nil) { return nil }
        if ((bean?.roleId ?? "").isEmpty){return nil}
        guard let aiRole = try await BackupsManager.shared.getDelegateConfig()?.getAiRole(roleId: bean?.roleId ?? "") else { return nil }
        return RoleBean.get(aiRole)
    }
    
    //根据来电，获取最新的AiRoleBean
    static func getRole(_ bean: CallHistoryBean?) async throws -> AiRoleBean? {
        if (bean == nil) { return nil }
        if (bean?.aiRole == nil ){return nil}
        guard let aiRole = try await BackupsManager.shared.getDelegateConfig()?.getAiRole(roleId: bean?.aiRole?.objectId ?? "") else { return nil }
        return aiRole
    }
    
    static func dealPicture(_ bean: DiaryBean, _ isRequestDetail: Bool) async throws {
        
    }
    
    //处理图片
    static func dealPicture(_ list: [DiaryBean], _ isRequestDetail: Bool) async throws {
        var listPicture : [CloudPictureBean] = []
        //forEach 不能异步，所以需要使用这种方式
        for diary in list {
            do {
                let listDiary = try await BackupsManager.shared.getDelegateDiary()?.queryPicture(diaryId: diary.objectId ?? "", userId: diary.userId ?? "", limit: 0) ?? []
                listPicture.append(contentsOf: listDiary)
                // 处理 listDiary
            } catch {
                // 处理错误
            }
        }
        if isRequestDetail {
            //todo 批量获取图片详情,不能频繁请求，所以把多个日记下的图片进行整合请求
        }
        for diary in list {
            let listDiaryPicture = listPicture.filter{ $0.diaryId == diary.objectId}
            diary.listDiaryPicture = listDiaryPicture
        }
        //todo 图片获取完成后，开始获取声音
        //        getSound(listDiary, isRequestDetail, type)
    }
    
    
    //处理评论
    static func dealComment(_ list: [DiaryBean]) async throws {
        for diary in list {
            do {
                if diary.temOther?.isEmpty == false {
                    showLog("评论使用临时数据")
                } else {
                    var listTemComment = [DiaryTemComment]()
                    if diary.roleType == IRoleType.USER.rawValue {
                        
                        if diary.isMultiple() {
                            //多人评论
                            //获取最近评论
                            showLog("评论请求接口数据")
                            //遍历角色，获取对于的角色评论
                            let listRoleRule =  diary.aiRule?.listAiRole ?? []
                            for it in listRoleRule {
                                let aiRoleId = it.roleId ?? ""
                                let list = try await BackupsManager.shared.getDelegateDiary()?.queryDiaryComment(diaryId: diary.objectId ?? "", aiRoleId: aiRoleId, pageNo: 0, pageSize: 1)
                                //先添加日记回复
                                if (it.content ?? []).isEmpty == false {
                                    let aiRole = try await BackupsManager.shared.getDelegateConfig()?.getAiRole(roleId: aiRoleId)
                                    let temBean = DiaryTemComment()
                                    temBean.avatar = aiRole?.avatar
                                    temBean.name = aiRole?.name
                                    temBean.content = it.content?[0] ?? ""
                                    temBean.first = true
                                    temBean.bot = true
                                    temBean.aiRoleId = aiRoleId
                                    listTemComment.append(temBean)
                                }
                                //添加评论
                                for commentBean in list ?? [] {
                                    listTemComment.append(try await convertComment(commentBean, aiRoleId))
                                }
                            }
                            
                        } else if diary.aiChat2 != nil && diary.aiChat2?.aiRole != nil {
                            //单人评论
                            //获取最近评论
                            showLog("评论请求接口数据")
                            let list = try await BackupsManager.shared.getDelegateDiary()?.queryDiaryComment(diaryId: diary.objectId ?? "", pageNo: 0, pageSize: 3)
                            let aiRole = try await BackupsManager.shared.getDelegateConfig()?.getAiRole(roleId: diary.aiChat2?.aiRole?.objectId)
                            let aiRoleId = aiRole?.objectId ?? ""
                            //先添加日记回复
                            let temBean = DiaryTemComment()
                            temBean.avatar = aiRole?.avatar
                            temBean.name = aiRole?.name
                            temBean.content = diary.getAiText()
                            temBean.first = true
                            temBean.bot = true
                            temBean.aiRoleId = aiRoleId
                            listTemComment.append(temBean)
                            //添加评论
                            for commentBean in list ?? [] {
                                listTemComment.append(try await convertComment(commentBean, aiRoleId))
                            }
                        } else if(diary.getAiText() ?? "").isEmpty {
                            //最早旧数据
                            //旧数据
                            let commentBean = DiaryCommentBean()
                            commentBean.content = diary.getAiText()
                            listTemComment.append(try await convertComment(commentBean, nil))
                        }
                        
                    } else {
                        //ai日记获取最近评论
                        showLog("评论请求接口数据")
                        let list = try await BackupsManager.shared.getDelegateDiary()?.queryDiaryComment(diaryId: diary.objectId ?? "", pageNo: 0, pageSize: 3)
                        let aiRoleId = diary.roleId
                        //添加评论
                        for commentBean in list ?? [] {
                            listTemComment.append(try await convertComment(commentBean, aiRoleId))
                        }
                    }
                    diary.temOther = listTemComment
                }
            } catch {
                // 处理错误
            }
        }
    }
    
    
    //转换评论
    private static func convertComment(_ bean: DiaryCommentBean, _ aiRoleId: String?) async throws -> DiaryTemComment {
        let roleBean = try await getRole(bean)
        let temBean = DiaryTemComment()
        temBean.avatar = roleBean?.avatar
        temBean.name = roleBean?.showName
        temBean.content = bean.content
        temBean.first = aiRoleId == nil // 如果ai为空，那么评论就是第一个，旧数据
        temBean.bot = roleBean?.isBot() ?? true  //默认为ai
        temBean.aiRoleId = aiRoleId
        return temBean
    }
    
    //CloudPictureBean 转为为可以显示的MediaItem 试图
    static func getMediaItem(_ pictrue: CloudPictureBean?)-> MediaItem? {
        if pictrue == nil {
            return nil
        }
        var mediaItems : MediaItem? = nil
        if BackupsManager.shared.isLocalBackups() {
            if pictrue!.isVideo() {
                //视频
                if let url = VideoFileManager.loadVideoURL(pictrue!.url ?? "") {
                    let item = MediaItem(type: .localVideo(url))
                    mediaItems = item
                }
            } else {
                //图片
                if let localPath = ImageFileManager.loadImagePath(pictrue!.thumbnail ?? ""), !localPath.isEmpty {
                       mediaItems = MediaItem(type: .localImagePath(localPath))
                   } else if let image = ImageFileManager.loadImage(pictrue!.thumbnail ?? "") {
                       // 路径无效，尝试加载图片
                       mediaItems = MediaItem(type: .localImage(image))
                   }
            }
            
        } else {
            let item = MediaItem(type: .networkImage(pictrue!.thumbnail ?? "",pictrue!.url ?? "", pictrue!.isVideo()))
            mediaItems = item
        }
        return mediaItems
    }
    
    static func getMediaItem(_ pictrue: EmojiPictureBean?)-> MediaItem? {
        if pictrue == nil {
            return nil
        }
        var mediaItems : MediaItem? = nil
        if BackupsManager.shared.isLocalBackups() {
            if pictrue!.isVideo() {
                //视频
                if let url = VideoFileManager.loadVideoURL(pictrue!.path ?? "") {
                    let item = MediaItem(type: .localVideo(url))
                    mediaItems = item
                }
            } else {
                //图片
                if let localPath = ImageFileManager.loadImagePath(pictrue!.path ?? ""), !localPath.isEmpty {
                       mediaItems = MediaItem(type: .localImagePath(localPath))
                   } else if let image = ImageFileManager.loadImage(pictrue!.path ?? "") {
                       // 路径无效，尝试加载图片
                       mediaItems = MediaItem(type: .localImage(image))
                   }
            }
            
        } else {
            let item = MediaItem(type: .networkImage(pictrue!.path ?? "",pictrue!.path ?? "", pictrue!.isVideo()))
            mediaItems = item
        }
        return mediaItems
    }
}
